#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <functional>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include "Log.hpp"
#include "nocopy.hpp"
#include "InetAddr.hpp"

using namespace log_ns;

enum {
    SOCKET_ERROR = 1,
    BIND_ERROR
};

const int gsockfd = -1;
const uint16_t glocalport = 8888;

using server_task_t = std::function<void(int, const std::string&, InetAdrr&)>;

// 网络中的很多东西不建议直接进行拷贝，所以设计我们的类的时候
// 将其设置为不可拷贝的类
// 一般服务器主要用来进行网络数据读取和写入、IO的
// 我们可以将服务器的IO逻辑和业务逻辑解耦
class UdpServer : public nocopy {
private:
    std::string ServerEcho(struct sockaddr_in& peer) {
        // 获取发送方的ip port
        InetAdrr addr(peer);
        std::string echo("[");
        echo += addr.Ip();
        echo += " ";
        echo += std::to_string(addr.Port());
        echo += "]> ";
        return echo;
    }

public:
    // 构造函数传入ip和port
    UdpServer(server_task_t task, const std::string& ip, uint16_t port = glocalport) 
        : _task(task),
          _sockfd(gsockfd),
          _localip(ip),
          _localport(port),
          _isrunning(false)
    {}

    void Init() {
        // 先创建 sockfd 文件，使用如下接口的最后一个参数设置为0，
        // 会自动推测是哪个协议
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0) {
            LOG(FATAL, "Create sockfd fail\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "Create Socket success\n");

        // 绑定我们的信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY; // 将ip地址设置为0，可以进行任意ip绑定
        // local.sin_addr.s_addr = inet_addr(_localip.c_str());
        local.sin_port = htons(_localport);
        socklen_t len = sizeof(local);

        int n = ::bind(_sockfd, (struct sockaddr*)&local, len);
        if (n < 0) {
            LOG(FATAL, "Bind socket fail, %s\n", strerror(errno));
            exit(BIND_ERROR);
        }
        LOG(INFO, "Bind Socket success\n");
    }

    void Start() {
        _isrunning = true;
        // 需要收消息
        while (_isrunning) {
            struct sockaddr_in peer;
            memset(&peer, 0, sizeof(peer));
            socklen_t len = sizeof(peer);
            // peer.sin_family = AF_INET;
            // peer.sin_addr.s_addr
            char buff[1024];
            int n = recvfrom(_sockfd, buff, sizeof(buff) - 1, 0, (struct sockaddr*)&peer, &len);
            if (n > 0) {
                InetAdrr addr(peer);
                buff[n] = 0;
                std::string messeage = buff;
                // 将消息转发出去
                LOG(INFO, "begin to forword\n");
                _task(_sockfd, messeage, addr);
                LOG(INFO, "return server\n");
            }
        }
        _isrunning = false;

    }

    ~UdpServer() {
        if (_sockfd > 0)
            ::close(_sockfd);
    }
private:
    int _sockfd;
    std::string _localip;
    uint16_t _localport;
    bool _isrunning;

    server_task_t _task;
};